<?php

namespace app\index\controller;

use addons\wechat\model\WechatCaptcha;
use app\common\controller\Frontend;
use app\common\library\Ems;
use app\common\library\Sms;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;
use think\Db;

use app\common\model\House;
use app\common\model\Student;
use app\admin\model\Teacher;
/**
 * 澡堂申请
 */
class Bathhouse extends Frontend
{

    protected $noNeedLogin = ['index','check', 'into', 'leave'];
    protected $noNeedRight = ['*'];
    protected $layout = 'weiui';

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;
        $this->assign('pageTitle','浴室预约');
    }

    /**
     * 空的请求
     * @param $name
     * @return mixed
     */
    public function _empty($name)
    {
        $data = Hook::listen("user_request_empty", $name);
        foreach ($data as $index => $datum) {
            $this->view->assign($datum);
        }
        return $this->view->fetch('user/' . $name);
    }

    /**
     * 预约登记
     */
    public function index()
    {

        $list = House::where('id<5')->select();
        $url = $this->request->request('url', '');
        if ($this->request->isPost()) {

            $username = $this->request->post('username');
            $sid = $this->request->post('sid');
            $sex = $this->request->post('sex');
            $house_name = $this->request->post('house_name');

            $bathhouse = Db::name('bathhouse')->where(['name'=>$house_name,'status'=>1])->find();

            //学生
            // $sult = Student::get_info($username,$sid);
            // if(empty($sult)){
            //     //教师
            //     $su = Teacher::get_info($username,$sid);
            //     if(empty($su)){
            //         $this->error('该人员不存在,重新输入!');       
            //     }
            // }
    
            //获取开始预约时间，和结束预约时间
            $begin_time= $bathhouse['begin_time'];//开始时间
            $begin_fen= $bathhouse['begin_fen'];//开始分钟
            $begin_times = strtotime($begin_time.':'.$begin_fen);

            $end_time= $bathhouse['end_time'];//结束时间
            $end_fen= $bathhouse['end_fen'];//结束分钟
            $end_times = strtotime($end_time.':'.$end_fen);
            //echo $end_times."###<br/>";

            //获取当前的时分
            $local_time = strtotime(date("H:i"));

            if($local_time<$begin_times||$local_time>$end_times)
            {
                $this->error(__('未到预约时间'));
            }

            if($sex=='男'){
                if($bathhouse['man']==0){
                    $this->error(__($house_name.'暂不支持男生预约'));
                }else{
                    //统计预约的个数
                    $reserve_count=Db::name('bathhouse_record')
                    ->where(['sex'=>'男','bathhouse_id'=>$bathhouse['id'],'states'=>1])->count();
                    if($reserve_count>=$bathhouse['man']){
                        $this->error(__('预约人数已满,请稍后再试'));
                    }
                }
            }
            if($sex=='女'){
                if($bathhouse['woman']==0){
                    $this->error(__($house_name.'暂不支持女生预约'));
                }else{
                    $reserve_count=Db::name('bathhouse_record')
                    ->where(['sex'=>'女','bathhouse_id'=>$bathhouse['id'],'states'=>1])->count();
                    if($reserve_count>=$bathhouse['woman']){
                        $this->error(__('预约人数已满,请稍后再试'));
                    }
                }
            }

            $isset = Db::name('bathhouse_record')->where(['nickname'=>$username, 'sex'=>$sex,'sid' => $sid,'states'=>1])->find();
            if(isset($isset)){
                $this->error(__('已预约不可重复预约'));
            }
        
            // //不算本次添加，计算有几次忘记。离开的时候未扫码
            $count =Db::name('bathhouse_record')->where(['nickname'=>$username, 'sex'=>$sex,'bathhouse_id'=>$bathhouse['id'],'sid' => $sid,'leave_states'=>0])->count();
            $insert = [
                'nickname'  => $username,
                'sid'  => $sid,
                'sex'  => $sex,
                'bathhouse_name'  => $house_name,
                'bathhouse_id' =>$bathhouse['id'],
                'add_time'=>time(),
                'update_time'=>time(),
                'states'=>1
            ];
            $result = Db::name('bathhouse_record')->insertGetId($insert);//$this->auth->shower($username,$sid);
            if ($result) {

                // $where_['nickname']= $username;
                // $where_['sid']=$sid;
                // $where_['states']=1;
                $info= Db::name('bathhouse_record')->find($result);
                //从site.php 文件中获取
                $reserve_overdue_time= $bathhouse['reserve_losed_time'];
                $add_time= date('Y-m-d H:i:s',$info['add_time']);
                $data['times'] = $reserve_overdue_time;
                $data['add_time']= $add_time;
                $data['in_time'] = date('Y-m-d H:i:s', strtotime('+'.$reserve_overdue_time.'minute',$info['add_time']));
                //获取该学生是否有离开忘记扫码的情况
                $data['count'] = $count;

                $this->success(__('预约成功'), $url ? $url : url('user/index'),$data);                
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('list',$list);
        $this->view->assign('url', $url);
        // $this->view->assign('title', __('Register'));
        return $this->view->fetch();
    }


    /**
     * 预约登记
     */
    public function check()
    {

        $url = $this->request->request('url', '');
        if ($this->request->isPost()) {

            $username = $this->request->post('username');
            $sid = $this->request->post('sid');
            $sex = $this->request->post('sex');
            $house_name = $this->request->post('house_name');

            $bathhouse = Db::name('bathhouse')->where(['name'=>$house_name,'status'=>1])->find();
            $where_['nickname']= $username;
            $where_['sid']=$sid;
            $where_['into_states']=0;//未进入
            $where_['sex']= $sex;
            $where_['bathhouse_name']=$house_name;
            $info= Db::name('bathhouse_record')->where($where_)->order('id desc')->find();
            if ($info) {
                //定时任务已经改为过期
                if($info['states']==2)
                {
                    $this->error('预约已过期,请重新预约');
                }
                $reserve_overdue_time = $bathhouse['reserve_losed_time'];
                $minute=floor((time()-$info['add_time'])%86400/60);
                //echo "相差分钟数：".$minute."分钟<br/><br/>";                
                $timediff = time()-$info['add_time'];
                $days = intval($timediff/86400);

                //计算相差的时间为$site_time以上，就改为过期。
                if($minute>$reserve_overdue_time||$days!=0)
                {
                    //更新为已过期
                    $row = Db::name('bathhouse_record')->where(['id'=>$info['id']])-> update(['states'=>2]);
                    $this->error('预约已过期,请重新预约');
                }
                $add_time= date('Y-m-d H:i:s',$info['add_time']);
                $data['in_time'] = date('Y-m-d H:i:s', strtotime('+'.$reserve_overdue_time.'minute',$info['add_time']));
                $data['times'] = $reserve_overdue_time;
                $data['add_time']= $add_time;
                $this->success(__('预约成功'), $url ? $url : url('user/index'),$data);                
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
    }


    /**
     * 进入浴室
     *
     * @param string $username  账号
     * @param string $sid 学号
     */    
    public function into($ids  = null)
    { 
        $url = $this->request->request('url', '');        
        if ($this->request->isPost())
        {
            $username = $this->request->post('username');
            $sid = $this->request->post('sid');
            $bathhouse = Db::name('bathhouse')->find($ids);

            $where['nickname'] = $username;
            $where['sid'] = $sid;
            $where['bathhouse_id']=$ids;
            $row = Db::name('bathhouse_record')->where($where)->order('id desc')->find();
            if(!empty($row)){
                if($row['states']==1){
                    //已进入，未离开
                    if($row['into_states']==1&&$row['leave_states']==0)
                    {
                        $this->error('在浴室中,还未离开');
                    }
                    //从site.php 文件中获取
                    //验证预约时间是否过期了
                    $reserve_overdue_time= $bathhouse['reserve_losed_time'];
                    $minute=floor((time()-$row['add_time'])%86400/60);
                    $timediff = time()-$row['add_time'];
                    $days = intval($timediff/86400);

                    //计算相差的时间为$site_time以上，就改为过期。
                    if($minute>$reserve_overdue_time||$days!=0)
                    {
                        //更新为已过期
                        Db::name('bathhouse_record')->where(['id'=>$row['id']])-> update(['states'=>2]);
                        $this->error('预约已过期,请重新预约');
                    }                    
                    //处理进入状态
                    $params['into_time']= time();
                    $params['into_states']=1;
                    Db::name('bathhouse_record')->where(['id'=>$row['id']])->update($params);
                    $this->success(__('进入成功'));
                }else if($row['states']==0){
                    //还未预约
                    $this->error(__('请先预约再进入'));
                }else{
                    //已过期，重新预约
                    $this->error(__('已过期，重新预约'));
                }                
            }else{
                $this->error(__('还未预约'));
            }
        }
        $this->view->assign('url', $url);
        $this->assign('ids', $ids);
        $this->assignConfig('ids', $ids);
        return $this->view->fetch(); 
    }


    /**
     * 离开浴池
     *
     * @param string $username  账号
     * @param string $sid 学号
     * 释放预约名额 
     */     
    public function leave($ids  = null)
    {
        $url = $this->request->request('url', '');        
        if ($this->request->isPost())
        {
            $username = $this->request->post('username');
            $sid = $this->request->post('sid'); 

            $where['nickname'] = $username;
            $where['sid'] = $sid;
            // $where['into_states']=1;
            // $where['leave_states']=0;
            $where['bathhouse_id']=$ids;
            $row = Db::name('bathhouse_record')->where($where)->order('id desc')->find();
            if(!empty($row) && $row['into_states']==1 && $row['leave_states']==0 && $row['states']==1){
                //处理离开状态，做记录。
                $params['leave_time']= time();
                $params['leave_states']=1;
                $params['states']=0;
                Db::name('bathhouse_record')->where(['id'=>$row['id']])->update($params);
                $this->success(__('离开成功'));
            }else if(!empty($row) && $row['into_states']==0 && $row['leave_states']==1 && $row['states']==2){ 
                //定时任务已经更新成离开
                $params['leave_time']= time();
                $params['leave_states']=1;
                $params['states']=0;
                Db::name('bathhouse_record')->where(['id'=>$row['id']])->update($params);
                $this->success(__('离开成功'));
            }else{
                //找不到这条记录，提示错误
                $this->error(__('先进入,再离开!'));            
            } 
        }        
        $this->view->assign('url', $url);
        $this->assignConfig('ids', $ids);
        return $this->view->fetch(); 

    }    
}
